package com.dylan.历史.guava;

import com.dylan.历史.util.LogUtil;
import com.dylan.历史.util.SleepUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: ankang
 * @Date: 2019/3/8 11:17
 * @Description:
 */
public class 缓存 {

    // 定义缓存
    static LoadingCache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(10000)
            .expireAfterWrite(5, TimeUnit.SECONDS) // 设置过期时间，过期后，等待缓存加载完毕所有线程才能继续访问
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String k) throws Exception {
                    LogUtil.info("加载缓存，key=" + k);
                    SleepUtils.seconds(5);
                    return k + "-" + DateFormatUtils.format(new Date(), "HH:mm:ss");
                }
            });

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(20);

        // 预先设置缓存
        Map<String, String> map = new HashMap<>();
        map.put("abc0", "123");
        map.put("abc1", "234");
        cache.putAll(map);

        // 并发获取缓存
        for (int i = 0; i < 1000; i++) {
            final int ii = i;
            executor.execute(() -> {
                SleepUtils.milliseconds(100);
                LogUtil.info(cache.getUnchecked("abc" + (ii % 2)));
            });
        }
    }
}
